package espacokidsadm.web.filter;


import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import espacokidsadm.util.JPAUtil;

public class ConexaoJPAFilter implements Filter {

	private EntityManagerFactory factory;
	
	@Override
	public void init(FilterConfig config) throws ServletException {
		//this.factory = Persistence.createEntityManagerFactory("espacokidsadm");
		this.factory = JPAUtil.getEntityManagerFactory();
	}
	

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
		FilterChain chain) throws ServletException {
		
		EntityTransaction transaction = null;
		EntityManager manager = this.factory.createEntityManager();
		try{
			request.setAttribute("em", manager);
			transaction = manager.getTransaction();
			transaction.begin();
			
			chain.doFilter(request, response);
			
			transaction.commit();
		}catch(Exception ex) {
			if(transaction != null && transaction.isActive()) {
				transaction.rollback();
			}
		}finally {
			manager.close();
		}
	}

	@Override
	public void destroy() {
		this.factory.close();
	}


}
